/**
 * Copyright (c) 2010-2011 Pierre Labatut
 *
 * This file is part of Space-Chronicles project.
 *
 * Space-Chronicles-Chronicles is free software: you can redistribute it and/or modify it
 * under the terms of its license which may be found in the accompanying
 * LICENSE file or <http://code.google.com/p/space-chronicles/>.
 */
package space.app.common;

import java.util.prefs.Preferences;
import javax.swing.JFrame;

/**
 *
 * @author Pierre
 */
public class Options {

    final public String ip;
    final public int port;
    final public int fov;
    
    public Options(String ip, int port, int fov) {

        if (!isValidIp(ip)) {
            throw new IllegalArgumentException();
        }
        if (!isValidPort(port)) {
            throw new IllegalArgumentException();
        }
        if (!isValidFov(fov)) {
            throw new IllegalArgumentException();
        }

        this.ip = ip;
        this.port = port;
        this.fov = fov;
    }

    static boolean isValidFov(int fov) {
        return fov > 0 && fov < 180;
    }

    static boolean isValidPort(int port) {
        return port >= 1 && port <= 65535;
    }

    static boolean isValidIp(String ip) {
        return ip != null && !ip.isEmpty();
    }

    public Options showDialog(JFrame father) {
        final OptionsDialog preferenceDialog =
                new OptionsDialog(father, ip, port, fov);
        
        preferenceDialog.setVisible(true);
        return preferenceDialog.buildOptions();
        
    }

    public void writePreferences(Preferences node) {
        if (node == null) {
            throw new NullPointerException();
        }
        node.put("ip", ip);
        node.putInt("port", port);
        node.putInt("fov", fov);
    }

    public static Options readPreferences(Preferences node) {
        if (node == null) {
            throw new NullPointerException();
        }
        return new Options(
                node.get("ip", "0.0.0.0"),
                node.getInt("port", 6001),
                node.getInt("fov", 90));
    }

    void startServer(Server server) {
        if (server == null) {
            throw new NullPointerException();
        }
        server.start(ip,port);
    }
}
